package helpers;

import objects.Domino;
import objects.DominoGame;
import objects.Player;

public class GameThread extends Thread {
	
	private DominoGame dominoGame;
	private Boolean gameNotFinished;
	
	public GameThread(DominoGame game){
		this.dominoGame= game;
		gameNotFinished=true;
	}
	
	
	public void broadcastStartOfGame(){
		System.out.println("Starting the game already!");
		int a =12;
		
		Domino initialTile = Domino.findDomino(a, a);
		
		while(initialTile==null){
			a--;
			initialTile = Domino.findDomino(a, a);
		}
		
		for (Player p : dominoGame.players) {

			GamerThread gamerthread = p.getGameThread();

			//gamerthread.answer("StartGame");
			System.out.println("sorting dominoes");
			dominoGame.getDominoesSorter().sortDominoes();
			
			System.out.println("giving dominoes to players");
			gamerthread.answer("tiles_" + dominoGame.getSetSize() + "_"
					+ p.getDominoSetAsString());
			
			System.out.println("tiles_" + dominoGame.getSetSize() + "_"
					+ p.getDominoSetAsString());
			
			System.out.println("telling players their names and lines");
			
			for(Player q : dominoGame.players){
				int index = dominoGame.players.indexOf(q)+1;
				gamerthread.answer("players_"+q.getName()+"_"+index);
				
			}
			System.out.println("telling players the initial tile");
			gamerthread.answer("tile_["+initialTile.getFirst()+","+initialTile.getSecond()+"]");
			

		}
		
	}
	
	public void run(){
		
		try {
			sleep(10000);
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		broadcastStartOfGame();
		
		while(gameNotFinished){
			
			for(Player p : dominoGame.players){
				
				p.getGameThread().setActive(true);
				try {
					sleep(90);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			
		}
		
	}
	
}
